package org.hutb.community.controller;

import org.hutb.community.entity.DiscussPost;
import org.hutb.community.entity.Page;
import org.hutb.community.entity.User;
import org.hutb.community.service.DiscussPostService;
import org.hutb.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName HomeCotroller
 * @Description
 * @Author xubo
 * @Date 2021/11/24 23:18
 *
 *   论坛首页 控制器
 *
 */
@Controller
public class HomeController {

    @Autowired
    private UserService userService;

    @Autowired
    private DiscussPostService discussPostService;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page){
        //在 index.html中, 分页中的下一页,上一页等页面跳转中, 在url后面拼 /index?current=3
        //因为Page 类中有实例变量 current, 所以当页面回传current参数时, Spring会使用Page实例去封装
        page.setRows(discussPostService.selectDiscussPostRows(0));
        page.setPath("/index");
        System.out.println("从页面传回来的current参数:"+page.getCurrent());

        //将帖子按分页要求 封装成list集合
        List<DiscussPost> list = discussPostService.selectDiscussPosts(0,page.getOffset(),page.getLimit());
        List<Map<String,Object>> discussPosts = new ArrayList<>();
        if (list != null){
            for (DiscussPost post : list){
                Map<String,Object> map = new HashMap<>();
                map.put("post",post);
                User user = userService.findUserById(post.getUserId());
                map.put("user",user);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        return "/index";
    }

}
